/*
 * @描述: 登录页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import Link from 'umi/link';
import { Alert, Modal, Row, Col, Input, message } from 'antd';
import LoginComponent from '@/components/Login';
import styles from './Login.less';

const { Tab, Tenant, UserName, Password, Mobile, Captcha, Submit } = LoginComponent;

@connect(({ login, loading }) => ({
  login,
  submitting: loading.effects['login/login']
}))
class Login extends Component {
  state = {
    type: 'account',
    autoLogin: true,
    imgUrl: '/api/account/captcha/generateImageCaptcha',
    captchaTip: false
  };

  handleImg = () => {
    this.setState({ imgUrl: `/api/account/captcha/generateImageCaptcha?${Math.random()}` });
  }

  onTabChange = type => {
    this.setState({ type });
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      this.loginForm.validateFields(['mobile'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          dispatch({
            type: 'login/getCaptcha',
            payload: values.mobile,
          }).then(resolve).catch(reject);

          Modal.info({
            title: formatMessage({ id: 'app.login.verification-code-warning' })
          });
        }
      });
    });

  handleSubmit = (err, values) => {
    const { type } = this.state;

    if (!values.mobile) {
      if (!this.state.charCaptcha) {
        this.setState({
          captchaTip: true
        });
        return;
      }
    }

    if (!err) {
      const { dispatch } = this.props;

      if (values.username) {
        dispatch({
          type: 'login/compareCaptcha',//比对验证码
          payload: {
            charCaptcha: this.state.charCaptcha
          }
        }).then(response => {
          if (response.message == 'success') {
            dispatch({
              type: 'login/login',
              payload: {
                ...values,
                type
              }
            });
            this.setState({
              captchaTip: false
            });
          } else {
            message.warning(response.message);
            this.handleImg();
          }
        });
      } else {
        dispatch({
          type: 'login/login',
          payload: {
            ...values,
            type
          }
        });
      }
    }
  };

  onChange = e => {
    const { value } = e.target;
    this.setState({
      charCaptcha: value,
      captchaTip: false
    });
  };

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked
    });
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  render() {
    const { login, submitting } = this.props;
    const { type, autoLogin } = this.state; // NOSONAR
    return (
      <div className={styles.main}>
        <LoginComponent
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={form => {
            this.loginForm = form;
          }}
        >
          <Tab key="account" tab={formatMessage({ id: 'app.login.tab-login-credentials' })}>
            {login.status === 'error' &&
              login.type === 'account' &&
              !submitting &&
              this.renderMessage(formatMessage({ id: 'app.login.message-invalid-credentials' }))}
            <Tenant
              name="tenantCode"
              placeholder={`${formatMessage({ id: 'app.systenant.tenant-code' })}`}
              defaultValue='10001'
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.tenant-code.required' }),
                }
              ]}
            />
            <UserName
              name="username"
              defaultValue="reactadmin"
              placeholder={`${formatMessage({ id: 'app.login.username' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.username.required' }),
                }
              ]}
            />
            <Password
              name="password"
              defaultValue="666888"
              placeholder={`${formatMessage({ id: 'app.login.password' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.password.required' }),
                }
              ]}
            />
            <Row gutter={8} style={{ paddingLeft: '2px', paddingBottom: this.state.captchaTip ? '0px' : '30px' }}>
              <Col span={16}>
                <Input
                  style={{ borderColor: this.state.captchaTip ? '#F5222D' : null }}
                  size="large"
                  maxLength={4}
                  placeholder={formatMessage({ id: 'form.verification-code.placeholder' })}
                  onChange={this.onChange}
                  onPressEnter={e => {
                    e.preventDefault();
                    this.loginForm.validateFields(this.handleSubmit);
                  }}
                />
              </Col>
              <Col span={8}>
                <img src={this.state.imgUrl} onClick={this.handleImg} alt={formatMessage({ id: 'form.verification-code.placeholder' })} width="120px" height="40px" />
              </Col>
            </Row>
            <Row gutter={8} style={{ display: this.state.captchaTip ? 'block' : 'none', paddingBottom: '20px' }}>
              <div style={{ paddingLeft: '8px', color: '#F5222D' }}>{formatMessage({ id: 'validation.verification-code.required' })}</div>
            </Row>
          </Tab>
          <Tab key="mobile" tab={formatMessage({ id: 'app.login.tab-login-mobile' })}>
            {login.status === 'error' &&
              login.type === 'mobile' &&
              !submitting &&
              this.renderMessage(
                formatMessage({ id: 'app.login.message-invalid-verification-code' })
              )}
            <Tenant
              name="tenantCode"
              placeholder={`${formatMessage({ id: 'app.systenant.tenant-code' })}`}
              defaultValue='10001'
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.tenant-code.required' }),
                }
              ]}
            />
            <Mobile
              name="mobile"
              placeholder={formatMessage({ id: 'form.phone-number.placeholder' })}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.phone-number.required' }),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({ id: 'validation.phone-number.wrong-format' }),
                }
              ]}
            />
            <Captcha
              name="smsCaptcha"
              placeholder={formatMessage({ id: 'form.verification-code.placeholder' })}
              countDown={120}
              onGetCaptcha={this.onGetCaptcha}
              getCaptchaButtonText={formatMessage({ id: 'form.get-captcha' })}
              getCaptchaSecondText={formatMessage({ id: 'form.captcha.second' })}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.verification-code.required' }),
                }
              ]}
            />
          </Tab>
          {/**
          <div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="app.login.remember-me" />
            </Checkbox>
          </div>
          */}
          <Submit style={{ marginTop: '0px' }} loading={submitting}>
            <FormattedMessage id="app.login.login" />
          </Submit>
          <div className={styles.other}>
            {/**
            <FormattedMessage id="app.login.sign-in-with" />
            <Icon type="alipay-circle" className={styles.icon} theme="outlined" title="可自行扩展" />
            <Icon type="taobao-circle" className={styles.icon} theme="outlined" title="可自行扩展" />
            <Icon type="weibo-circle" className={styles.icon} theme="outlined" title="可自行扩展" />
            */}
            <Link style={{ float: 'left' }} to="/user/forgotpassword">
              <FormattedMessage id="app.login.forgot-password" />
            </Link>
            <Link className={styles.register} to="/user/register">
              <FormattedMessage id="app.login.signup" />
            </Link>
          </div>
        </LoginComponent>
      </div>
    );
  }
}

export default Login;
